﻿// This source file is part of the atomdb project
// 
// Copyright (c) 2017 - 2022 pulsarware, All rights reserved.
// Copyright (c) 2017 - 2022 polarboy <polarboy@163.com>
// 
// See https://atomdb.com/LICENSE.txt for license information
// 
// Created by polarboy on 2023/12/02.

using System.Runtime.InteropServices;
using Microsoft.Extensions.Options;

namespace Pulsarware.ATOMDB.Packager;

public abstract class AbstractPackager : IPackager
{
   protected ToolChain? _toolChain;
   private readonly IHostDetector _hostDetector;
   private readonly Config _config;

   protected AbstractPackager(IHostDetector hostDetector, IOptions<Config> config)
   {
      _hostDetector = hostDetector;
      _config = config.Value;
   }
   
   public void Build()
   {
      DetectBuildHost();
      PrintBuildHostInfo();
      Cleanup();
      Configure();
      PreparePackageFiles();
      GeneratePackage();
   }

   protected virtual void DetectBuildHost()
   {
      var detectResult = _hostDetector.DetectAsync();
      detectResult.Wait();
      if (!detectResult.Result)
      {
         throw new Exception("Detect build host toolchain failed");
      }
      _toolChain = _hostDetector.ToolChainInfo();
   }
   
   protected abstract void Cleanup();
   protected abstract void Configure();
   protected abstract void Compile();
   protected abstract void PreparePackageFiles();
   protected abstract void GeneratePackage();

   protected virtual void PrintBuildHostInfo()
   {
      Console.WriteLine("--- Building ATOMDB with config: ---");
      Console.WriteLine("Target Operation System: {0}", Environment.OSVersion.VersionString);
      Console.WriteLine("Target Architectures: {0}", RuntimeInformation.OSArchitecture);
      Console.WriteLine("Make Tool: {0}", _config.UseNinja ? _toolChain!.NinjaBinary : _toolChain!.MakeBinary);
      Console.WriteLine("Release Version: {0}", _config.ReleaseVersion);
      Console.WriteLine("SourceDir: {0}", _config.SourceDir);
      Console.WriteLine("BuildDir: {0}", _config.BuildDir);
      Console.WriteLine("ShowBuildTime: {0}", _config.ShowBuildTime);
      Console.WriteLine("AppendVersionToPackageFilename: {0}", _config.AppendVersionToPackageFilename);
      Console.WriteLine("AppendDateToPackageFilename: {0}", _config.AppendDateToPackageFilename);
   }

   protected void InvokeCMake(string[] args)
   {
      
   }

   protected void InvokeMake(string[] args)
   {
      
   }

   protected void InvokeNinja(string[] args)
   {
      
   }

   protected void ReportError(string errorMsg)
   {
      
   }
}